import { nextTick } from 'vue'
import CookieUtil from '@/utils/cookieUtil.js'

const useAppStore = defineStore(
  'app',
  {
    state: () => ({
      sidebar: {
        opened: CookieUtil.getCookie('sidebarStatus') ? !!+CookieUtil.getCookie('sidebarStatus') : true,
        withoutAnimation: false,
        hide: false,
      },
      device: 'desktop',
      size: CookieUtil.getCookie('size') || 'default',
      reloadFlag: true,
    }),
    actions: {
      /**
       * @description 重载页面
       * @param duration
       */
      async reloadPage(duration = 0) {
        this.reloadFlag = false
        await nextTick()
        if (duration) {
          setTimeout(() => {
            this.reloadFlag = true
          }, duration)
        }
        else {
          this.reloadFlag = true
        }
        setTimeout(() => {
          document.documentElement.scrollTo({ left: 0, top: 0 })
        }, 100)
      },
      toggleSideBar(withoutAnimation) {
        if (this.sidebar.hide) {
          return false
        }
        this.sidebar.opened = !this.sidebar.opened
        this.sidebar.withoutAnimation = withoutAnimation
        if (this.sidebar.opened) {
          CookieUtil.setCookie('sidebarStatus', 1)
        }
        else {
          CookieUtil.setCookie('sidebarStatus', 0)
        }
      },
      closeSideBar({ withoutAnimation }) {
        CookieUtil.setCookie('sidebarStatus', 0)
        this.sidebar.opened = false
        this.sidebar.withoutAnimation = withoutAnimation
      },
      toggleDevice(device) {
        this.device = device
      },
      setSize(size) {
        this.size = size
        CookieUtil.setCookie('size', size)
      },
      toggleSideBarHide(status) {
        this.sidebar.hide = status
      },
    },
  })

export default useAppStore
